package com.vvitt.kotlinhiltcarhome.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import com.vvitt.kotlinhiltcarhome.adapter.CarBrandAdapter
import com.vvitt.kotlinhiltcarhome.adapter.FooterAdapter
import com.vvitt.kotlinhiltcarhome.databinding.FragmentHomeBinding
import com.vvitt.kotlinhiltcarhome.viewmodel.CarBrandViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import javax.inject.Inject


/**
 * A simple [Fragment] subclass.
 * Use the [HomeFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
@AndroidEntryPoint
class HomeFragment @Inject constructor() : Fragment() {

    private val viewModel by viewModels<CarBrandViewModel>()
    private val mAdapter by lazy {context?.let { CarBrandAdapter(it)}}


    private val mBinding : FragmentHomeBinding by lazy {
        FragmentHomeBinding.inflate(layoutInflater)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return mBinding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        context?.let {
//            mBinding.recyleView.adapter = mAdapter
            mBinding.recyleView.adapter = mAdapter?.withLoadStateFooter(FooterAdapter(mAdapter!!, it))
            viewModel.data.observe(viewLifecycleOwner,{
                mAdapter?.submitData(lifecycle,it)
            })

            lifecycleScope.launchWhenCreated {
                mAdapter?.loadStateFlow?.collectLatest { state ->
                    mBinding.swiperRefresh.isRefreshing = state.refresh is LoadState.Loading

                }
            }

            viewModel.data.observe(viewLifecycleOwner, Observer {
                mAdapter?.submitData(lifecycle,it)
                mBinding.swiperRefresh.isEnabled = false

            })


        }

    }
}